//
//  ZLDetailPoemViewController.m
//  LittleFairyPoet
//
//  Created by rimi on 15/9/8.
//  Copyright (c) 2015年 周林. All rights reserved.
//

#import "ZLDetailPoemViewController.h"
#import "ZLZhushiViewController.h"
#import "UIViewController+ADFlipTransition.h"
#import "UIImage+Clips.h"
#import <DCPathButton.h>
#import "WPReciteModelViewController.h"


#define COLLECTED_POEM_PATH NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject

typedef NS_ENUM(NSUInteger, ZLButtonSelected) {
    ZLButtonSelectedLast,
    ZLButtonSelectedExplain,
    ZLButtonSelectedNext,
    ZLButtonSelectedRecit,
};

@interface ZLDetailPoemViewController () <DCPathButtonDelegate>
{
    NSArray *_dataSource;
    NSMutableArray *_collectedPoemArray;
    NSString *_path;
}
@property (nonatomic, strong) UILabel * content /**< 诗正文 */;
@property (nonatomic, strong) UIButton * zhushiButton /**< 注释按钮 */;
@property (nonatomic, strong) UIButton * ceshiButton /**< 测试按钮 */;
@property (nonatomic, strong) UIButton * langduButton /**< 朗读按钮 */;
@property (nonatomic, strong) UIButton * nextButton /**< 下一首按钮 */;
@property (nonatomic, strong) UIScrollView * mainScrollView /**< 主滚动视图 */;
@property (nonatomic, strong) UILabel * titleLabel /**< 标题 */;
@property (nonatomic, strong) UILabel * author /**< 作者 */;
@property (nonatomic, strong) DCPathButton * menueButton /**< 菜单 */;
@property (nonatomic, strong) DCPathButton * menueBtnWithRecite; /**< 菜单带背诵 */

- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */
@end

@implementation ZLDetailPoemViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    CALayer *layer = [CALayer layer];
    layer.bounds = self.view.bounds;
    layer.position = self.view.center;
    layer.contents = (__bridge id)(IMAGE_CONTENT(@"背景5.jpg")).CGImage;
    [self.view.layer addSublayer:layer];
    [self.baseNavigationBar removeFromSuperview];
    [self.view addSubview:self.baseNavigationBar];
    self.baseNavigationBar.backgroundColor = [UIColor clearColor];
    [self initializeDataSource];
    [self initializeUserInterface];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

#pragma mark - private
- (void)initializeDataSource {
    
    _dataSource = self.poemArray;
    NSFileManager * manager = [NSFileManager defaultManager];
    _path = [COLLECTED_POEM_PATH stringByAppendingString:@"/CollectedPoem.plist"];
    if ([manager fileExistsAtPath:_path]) {
        _collectedPoemArray = [NSMutableArray arrayWithContentsOfFile:_path];
    } else {
        _collectedPoemArray = [NSMutableArray array];
    }
}

- (void)initializeUserInterface {
    self.view.backgroundColor = [UIColor whiteColor];
    [self.rightButton setImage:IMAGE_CONTENT(@"收藏导航心.png") forState:UIControlStateNormal];
    [self.rightButton setImage:IMAGE_CONTENT(@"心-实底.png") forState:UIControlStateSelected];
    [self.mainScrollView addSubview:self.content];
    [self.view addSubview:self.zhushiButton];
    [self.view addSubview:self.ceshiButton];
    [self.view addSubview:self.nextButton];
    [self.view addSubview:self.mainScrollView];
    [self.view addSubview:self.titleLable];
    [self.view addSubview:self.author];
    if (!self.poemDic[@"canpush"]) {
       [self.view addSubview:self.menueButton];
    } else {
        [self.view addSubview:self.menueBtnWithRecite];
    }
    self.mainScrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(_content.frame));
    if ([_collectedPoemArray containsObject:_poemDic]) {
        self.rightButton.selected = YES;
    }
    self.titleLable.font = [UIFont fontWithName:@"Kaiti" size:20];
    self.leftButton.frame = DHFlexibleFrame(CGRectMake(5, 15, 90, 50), YES);
    [self.leftButton setImage:IMAGE_CONTENT(@"返回主菜单.png") forState:UIControlStateNormal];
    self.rightButton.frame = DHFlexibleFrame(CGRectMake(230, 15, 90, 50), NO);
}

- (void)changeText {
    
    _titleLabel.text = _poemDic[@"title"];
    _author.text = [NSString stringWithFormat:@"%@·%@",_poemDic[@"chaodai"], _poemDic[@"zuozhe"]];
    _content.frame = DHFlexibleFrame(CGRectMake(20, 0, ORIGIN_WIDTH, 64), NO);
    NSString * text = _poemDic[@"content"];
    [text copy];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:_poemDic[@"content"]];
    paragraphStyle.lineSpacing = 10;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
    
    _content.attributedText = attributedString;
    [_content sizeToFit];
    CGPoint center = CGPointMake(ORIGIN_WIDTH / 2, _content.bounds.size.height / 2);
    if (center.y < self.view.center.y / 2) {
        center.y = self.view.center.y / 2;
    }
    _content.center = center;
    self.mainScrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(_content.frame));
}

#pragma mark - responds events
- (void)respondsToTabBarRightButton:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [_collectedPoemArray addObject:_poemDic];
        
        if ([_collectedPoemArray writeToFile: _path atomically:YES]) {
            
          [self initializeAlertControllerWithMessage:@"收藏成功"];
        } else {
            sender.selected = NO;
        }
    } else {
        
        [_collectedPoemArray removeObject:_poemDic];
        if ([_collectedPoemArray writeToFile:_path atomically:YES]) {
            
           [self initializeAlertControllerWithMessage:@"取消收藏成功"];
        } else {
            sender.selected = YES;
        }
    }
}
#pragma mark - <DCPathButtonDelegate>
- (void)pathButton:(DCPathButton *)dcPathButton clickItemButtonAtIndex:(NSUInteger)itemButtonIndex {
    switch (itemButtonIndex) {
        case ZLButtonSelectedLast:
        {
            _poemSerialNo --;
            if (_poemSerialNo < 0) {
                [self initializeAlertControllerWithMessage:@"已经是第一首了"];
                _poemSerialNo ++;
                return;
            }
            self.poemDic = _dataSource[_poemSerialNo];
            if (_poemDic[@"canpush"]) {
                if (self.menueButton.superview) {
                    [self.menueButton removeFromSuperview];
                }
                if (!self.menueBtnWithRecite.superview) {
                    [self.view addSubview:self.menueBtnWithRecite];
                }
            }else {
                if (self.menueBtnWithRecite.superview) {
                    [self.menueBtnWithRecite removeFromSuperview];
                }
                if (!self.menueButton.superview) {
                    [self.view addSubview:self.menueButton];
                }
            }
            [self changeText];
        }
            break;
        case ZLButtonSelectedExplain:
        {
            if (self.poemDic[@"yiwen"]) {
                ZLZhushiViewController *zhushiVC = [ZLZhushiViewController new];
                zhushiVC.poem = self.poemDic;
                [self.navigationController pushViewController:zhushiVC animated:YES];
            } else {
                [self initAlertControllerDismissWithMessage:@"暂未收录，敬请期待"];
            }
           
        }
            break;
        case ZLButtonSelectedNext:
        {
            _poemSerialNo ++;
            if (_poemSerialNo >= _dataSource.count) {
                [self initializeAlertControllerWithMessage:@"已经是最后一首了"];
                _poemSerialNo --;
                return;
            }
            self.poemDic = _dataSource[_poemSerialNo];
            if (_poemDic[@"canpush"]) {
                if (self.menueButton.superview) {
                    [self.menueButton removeFromSuperview];
                }
                if (!self.menueBtnWithRecite.superview) {
                    [self.view addSubview:self.menueBtnWithRecite];
                }
            } else {
                if (self.menueBtnWithRecite.superview) {
                    [self.menueBtnWithRecite removeFromSuperview];
                }
                if (!self.menueButton.superview) {
                    [self.view addSubview:self.menueButton];
                }
            }
            [self changeText];
        }
            break;
        case ZLButtonSelectedRecit:
        {
            WPReciteModelViewController * recitVC = [[WPReciteModelViewController alloc]init];
            recitVC.poemDict = _poemDic;
            recitVC.count = _poemSerialNo;
            recitVC.poemArray = _poemArray;
            [self.navigationController pushViewController:recitVC animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark - private method
- (CGFloat) culculateHeightWithText :(NSString *) text font:(UIFont *)font {
    CGRect rect = [text boundingRectWithSize:DHFlexibleSize(CGSizeMake(ORIGIN_WIDTH - 20, MAXFLOAT), NO) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : font} context:nil];
    return rect.size.height;
}

#pragma mark - getter
- (UILabel *)content {
    if (!_content) {
        _content = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ORIGIN_WIDTH, 64) adjustWidth:NO];
        _content.numberOfLines = 0;
        _content.textAlignment = NSTextAlignmentCenter;
        _content.font = [UIFont fontWithName:@"Kaiti" size:20];
        [self changeText];
    }
    return _content;
}

- (UIScrollView *)mainScrollView {
    if (!_mainScrollView) {
        _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 135, ORIGIN_WIDTH, ORIGIN_HEIGHT - 300) adjustWidth:NO];
    }
    return _mainScrollView;
}

- (UILabel *)titleLable {
    if (!_titleLabel) {
        
        _titleLabel = ({
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, 60, 180, 40) adjustWidth:NO];
            //label.backgroundColor = [UIColor orangeColor];
            label.textAlignment = NSTextAlignmentCenter;
            label.numberOfLines = 0;
            label.text = _poemDic[@"title"];
            label.font = [UIFont fontWithName:@"Kaiti" size:22];
            label.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:22];
            label;
        });
    }
    return _titleLabel;
}

- (UILabel *)author {
    if (!_author) {
        
        _author = ({
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(120, 100, 180, 40) adjustWidth:NO];
            label.textAlignment = NSTextAlignmentRight;
            label.numberOfLines = 0;
            label.text = [NSString stringWithFormat:@"%@·%@",_poemDic[@"chaodai"], _poemDic[@"zuozhe"]];
            label.font = [UIFont fontWithName:@"Kaiti" size:16];
            label;
        });
    }
    return _author;
}

- (DCPathButton *)menueButton {
    if (!_menueButton) {
        _menueButton = [[DCPathButton alloc]initWithButtonFrame:DHFlexibleFrame(CGRectMake(160, 480, 50, 50), NO) centerImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"添加菜单.png") radius:50] highlightedImage:nil];
        _menueButton.allowSounds = NO;
        DCPathItemButton *lastButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"上一首.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        DCPathItemButton *nextButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"下一首.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        DCPathItemButton *explainButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"注释.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        _menueButton.delegate = self;
        [_menueButton addPathItems:@[lastButton, explainButton, nextButton]];
    }
    return _menueButton;
}
- (DCPathButton *)menueBtnWithRecite {
    if (!_menueBtnWithRecite) {
        _menueBtnWithRecite = [[DCPathButton alloc]initWithButtonFrame:DHFlexibleFrame(CGRectMake(160, 480, 50, 50), NO) centerImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"添加菜单.png") radius:50] highlightedImage:nil];
        DCPathItemButton *lastButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"上一首.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        DCPathItemButton *nextButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"下一首.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        DCPathItemButton *explainButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"注释.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        DCPathItemButton *reciteButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"默写.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        _menueBtnWithRecite.delegate = self;
        [_menueBtnWithRecite addPathItems:@[lastButton, explainButton, nextButton, reciteButton]];
    }
    return _menueBtnWithRecite;
}

@end
